using System;
using System.Collections.Generic;
using System.Text;
using AntEater.ComponentModel.BuildElements;
using System.Collections.ObjectModel;
using System.IO;

namespace AntEater.Runtime.Tests.Services.Transformation
{
    /// <summary>
    /// Provides a set of Utilities.
    /// </summary>
    internal class Utilities
    {

        /// <summary>
        /// Dumps the build component tree.
        /// </summary>
        /// <param name="rootElements">The root elements.</param>
        /// <returns></returns>
        public static string DumpBuildComponentTree(Collection<IBuildElement> rootElements) {

            System.IO.TextWriter writer = new System.IO.StringWriter();
            
            foreach (IBuildElement element in rootElements) {
                DumpBuildComponentTreeLevel(element, writer,0);
            }

            return writer.ToString();
        }

        /// <summary>
        /// Copies an Stream into another Stream.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <param name="buffersize">The buffersize.</param>
        /// <returns>The number of Bytes copied.</returns>
        public static long CopyStream(Stream from, Stream to, int buffersize) {
            byte[] buffer = new byte[buffersize];
            long totalBytesCopied = 0;
            int bytesRead = 0;

            bytesRead = from.Read(buffer, 0, buffersize);

            while(bytesRead > 0){
                to.Write(buffer, 0, bytesRead);
                totalBytesCopied += bytesRead;
                bytesRead = from.Read(buffer, 0, buffersize);
            }

            return totalBytesCopied;
        }

        /// <summary>
        /// Dumps the build component tree level.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="writer">The writer.</param>
        /// <param name="level">The level.</param>
        private static void DumpBuildComponentTreeLevel(IBuildElement element, System.IO.TextWriter writer, int level) {

            string ident = "";

            for (int i = 0; i < level; i++) {
                ident += "\t";
            }

            writer.WriteLine(ident + element.GetType().Name);

            if (element is IContainerBuildElement) {

                IContainerBuildElement container = element as IContainerBuildElement;

                foreach (IBuildElement child in container.ChildElements) {
                    DumpBuildComponentTreeLevel(child,writer,level+1);
                }
            }

        }

    }
}
